<template>
  <div class="ProductsRelease">
    <h2>产品详情</h2>

    <div class="main">
      <a-form :form="form" @submit="handleSubmit">
        <h3>基本信息</h3>
        <div>
          <a-form-item
            :label-col="formItemLayout.labelCol"
            :wrapper-col="formItemLayout.wrapperCol"
            label="产品名称"
          >
            <a-input
              :maxLength=101
              v-decorator="[
              'productName',
              { rules: [{ required: true,message:'请输入产品名称' },
                { max:100,message:'该内容最多为100个字'}],
                initialValue:defultForm.productName },
              ]"
            />
          </a-form-item>
          <a-form-item
            :label-col="formItemLayout.labelCol"
            :wrapper-col="formItemLayout.wrapperCol"
            label="产品同义名称"
          >
            <a-input :maxLength=101 v-decorator="[ 'productSynonymName',
            { rules: [{ max:100,message:'该内容最多为100个字'}],initialValue:defultForm.productSynonymName }, ]" />
            <em>多个名称使用分隔符(;)进行区分</em>
          </a-form-item>
          <a-form-item
          required
          :label-col="formTailLayout.labelCol"
          :wrapper-col="{span:15}"
          label="产品类别"
        >
          <div class="clearfix">
            <a-form-item class="f-left mr-32" >
            <a-select placeholder="请选择" style="width: 250px" @change="handleChange" v-decorator="['productOneCategory',{ rules: productOneCategoryRules,initialValue:defultForm.productOneCategory}]">
              <a-select-option
                v-for="(item,index) in selectType"
                :key="index"
                :value="item.categoryNo"
              >{{ item.categoryName }}</a-select-option>
              </a-select>
            </a-form-item>
              <a-form-item class="f-left mr-32">
              <a-select placeholder="请选择" style="width: 250px" @change="handleChange1" v-decorator="['productSecondCategory',{ rules: productSecondCategoryRules,initialValue:defultForm.productSecondCategory},]">
                <a-select-option
                  v-for="(item, index) in selectType1"
                  :key="index"
                  :value="item.categoryNo"
                >{{ item.categoryName }}</a-select-option>
              </a-select>
              </a-form-item>
              <a-form-item class="f-left">
              <a-input
                  :maxLength=101
                  style="width:250px"
                  v-decorator="[
                    'productThirdCategory',
                    { rules: [{ max:100,message:'该内容最多为100个字'}],initialValue:defultForm.productThirdCategory },
                  ]"
                />
              </a-form-item>
              <!-- </a-form-item> -->
          </div><em>可输入小类，多个名称使用分隔符（;）进行区分</em>
        </a-form-item>
        <a-form-item
            :label-col="formTailLayout.labelCol"
            :wrapper-col="formTailLayout.wrapperCol"
            label="产品特征类别"
          >
            <a-select placeholder="请选择" style="width: 150px" v-decorator="['productTag',{
              initialValue:defultForm.productTag
            }]">
              <a-select-option v-for="(item) in reExamine" :value="item.key" :key="item.key">{{ item.label }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item
            :label-col="formTailLayout.labelCol"
            :wrapper-col="formTailLayout.wrapperCol"
            label="是否可定制"
          >
            <a-radio-group
              v-decorator="[
                'productOem',
                { rules: [{ required: true,message:'请选择' }],
                 initialValue:defultForm.productOem },
              ]"
            >
              <a-radio :value="1">是</a-radio>
              <a-radio :value="2">否</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="{span:8}" label="上市日期">
            <a-date-picker
              :disabled-date="disabledDate"
              v-decorator="[
                'publishDate',
                { rules: [{ required: true,message:'请选择上市日期' }],
                initialValue:defultForm.publishDate?defultForm.publishDate:null },
              ]"
            />
          </a-form-item>
          <a-form-item
            required
            class="clearfix"
            :label-col="formItemLayout.labelCol"
            :wrapper-col="{span:8}"
            label="价格"
          >
            <a-input
              suffix="元"
              class="f-left"
              style="width:220px"
              @change="inputChange"
              v-decorator="[
              'price',
              { rules: priceRules,initialValue:defultForm.price },
            ]"
            />
            <a-form-item class="f-left ml-20">
              <a-checkbox :checked="checkNick"  v-decorator="['isInterview']" @change="checkChange">面谈</a-checkbox>
            </a-form-item>
          </a-form-item>
          <a-form-item
            class="clearfix"
            required
            :label-col="formItemLayout.labelCol"
            :wrapper-col="{span:8}"
            label="供应上限"
          >
            <a-input
              class="f-left"
              style="width:220px"
              @change="inputChange1"
              v-decorator="[
                  'productCeiling',
                  { rules: productCeilingRules,initialValue:defultForm.productCeiling  },
                ]"
            />
            <a-form-item class="f-left ml-20">
              <!-- 是否限值供应（1 不限 0 默认） -->
              <a-checkbox
                :checked="checkNick1"
                @change="checkChange1"
                v-decorator="['productIslimited']"
              >不限</a-checkbox>
            </a-form-item>
          </a-form-item>
        </div>

        <h3><span style="color:red" class="mr-8">*</span>产品图片</h3>
        <a-form-item class="clearfix ml-50">
          <viewer :images="formLine.productFile">
            <div class="img-box mr-20 f-left" v-for="(item,index) in formLine.productFile" :key="index">
              <img :src="wengeGetImageUrl(item.fileUrl)" alt="">
              <a-icon class="close" type="close-circle"  @click="DelImag(item.id,index)"/>
            </div>
          </viewer>
          <!-- <div v-if="formLine.productFile.length<5" class="uploadlogo f-left">
            <a-upload
              v-decorator="['productFile',{ rules: [{ required: true,message:'请上传图片' }],initialValue:defultForm.productFile },]"
              list-type="picture-card"
              :action="UploadUrl"
              :headers="headers"
              :before-upload="beforeUpload"
              @change="handleChanger"
              :show-upload-list="false"
            >
                <a-icon type="plus" />
                <div class="ant-upload-text">
                  上传图片
                </div>
            </a-upload>
            最多上传5张图片
          </div> -->
        </a-form-item>

        <h3><span style="color:red" class="mr-8">*</span>资质荣誉</h3>
        <a-form-item class="clearfix ml-50">
          <viewer :images="formLine.honorFile">
            <div class="img-box mr-20 f-left" v-for="(item,index) in formLine.honorFile" :key="index">
              <img :src="wengeGetImageUrl(item.fileUrl)" alt="">
              <a-icon class="close" type="close-circle"  @click="DelImag1(item.id,index)"/>
            </div>
          </viewer>
          <!-- <div v-if="formLine.honorFile.length<10" class="uploadlogo f-left">
            <a-upload
              v-decorator="['honorFile',{ rules: [{ required: true,message:'请上传图片' }],initialValue:defultForm.honorFile },]"
              list-type="picture-card"
              :action="UploadUrl"
              :headers="headers"
              :before-upload="beforeUpload"
              @change="handleChanger1"
              :show-upload-list="false"
            >
                <a-icon type="plus" />
                <div class="ant-upload-text">
                  上传图片
                </div>
            </a-upload>
            最多上传10张图片
          </div>  -->
        </a-form-item>

        <h3>产品详情</h3>
        <div>
          <a-form-item
            :label-col="formTailLayout.labelCol"
            :wrapper-col="formTailLayout.wrapperCol"
            label="基本参数"
          >
            <a-input
              :maxLength=201
              type="textarea"
              :rows="10"
              v-decorator="[
                'productParam',
                { rules: [
                  { required: true,message:'请输入基本参数' },
                  { max:200,message:'该内容最多为200字'}
                ],initialValue:defultForm.productParam },
              ]"
            />
            <em>多个名称使用分隔符(;)进行区分</em>
          </a-form-item>
          <a-form-item :label-col="formTailLayout.labelCol" :wrapper-col="{ span:15 }" label="详细说明">
            <editor-bar :rows="10" v-decorator="['productDetails', { rules: [{ required: true,message:'请输入详细说明内容' }],
                  initialValue:defultForm.productDetails }]" ref="editor"></editor-bar>
          </a-form-item>
        </div>

        <h3>联系方式</h3>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="联系人"
        >
          <a-input
            v-decorator="[
              'contacts',
              { rules: [{ required: true,message:'请输入联系人' }],
              initialValue:defultForm.contacts },
            ]"
          />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="手机号码"
        >
          <a-input
            v-decorator="[
              'phone',
              { rules: [
                { required: true,message:'请输入手机号码' },
                {
                  pattern:  /^1[3456789]\d{9}$/,
                  message: '手机号码格式不正确'
                }
              ],initialValue:defultForm.phone },
            ]"
          />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="电子邮箱"
        >
          <a-input
            v-decorator="[
              'email',
              { rules:[
                {
                  pattern: /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/,
                  message: '邮箱格式不正确'
              }],initialValue:defultForm.email}
            ]"
          />
        </a-form-item>
        <!-- <a-form-item :wrapper-col="{ span: 12, offset: 4 }">
          <a-button class="mr-20" @click="clear">返回</a-button>
          <a-button type="primary" html-type="submit">提交</a-button>
        </a-form-item> -->
      </a-form>
    </div>
    <a-form-item :wrapper-col="{ span: 12, offset: 4 }">
      <a-button  @click="clear">返回</a-button>
    </a-form-item>
  </div>
</template>

<script>
const formItemLayout = {
  //label长度
  labelCol: { span: 4 },
  //input长度
  wrapperCol: { span: 8 }
};
const formTailLayout = {
  //label长度
  labelCol: { span: 4 },
  //input长度
  wrapperCol: { span: 12 }
};
import moment from "moment";
import EditorBar from "@/components/wangEnduit/index.vue";
import { GetByParent } from "@/apis/user/MaterialsDemand";
import { Updateproduct,GetproductDetail } from "@/apis/user/ProductInfo";
import { getToken } from "@/utils/auth"; // get token from cookie
export default {
  components: { EditorBar },
  data() {
    return {
      productId: "",
      UploadUrl: GolbUrl._BASE_URL_  + "wenge/microservice-supply-consumer-web/sysFile/upload",
      // UploadUrl: "http://10.204.124.107:8081/wenge/microservice-supply-consumer-web/sysFile/upload",

      headers: {
        Authorization: getToken(),
      },
      productOneCategoryRules:[{required:true,message:'请选择一级类别'}],
      productSecondCategoryRules:[{required:false,message:'请选择二级类别'}],
      priceRules:[ { required: false,message:'请输入价格' },
                   { 
                    pattern:/^(\+)?\d+(\.\d+)?$/,
                    message:'该内容必须为数字' } ],
      productCeilingRules:[{ required: false,message:'请输入上限数量' }],
      value: 1,
      checkNick: true,
      checkNick1: true,
      selectType: [],
      selectType1: [],
      formItemLayout,
      formTailLayout,
      form: this.$form.createForm(this),
      formLine: {
        productFile: [],
        honorFile: [],
      },
      reExamine: [
        {
          label: "重点新产品",
          key: 1
        },
        {
          label: "自主查新产品",
          key: 2
        },
        {
          label: "专利新产品",
          key: 3
        },
        {
          label: "其他",
          key: 4
        }
      ],
      defultForm:{}
      
    };
  },
  created() {
    this.GetByParentList();
    console.log(this.$route.query.id)
    if (this.$route.query.id) {
      this.productId= this.$route.query.id;
      this.GetproductDetail()
    }
  },
  methods: {
    //日期判断今天之前不可选（不包含今天）
    disabledDate(current) {
      // Can not select days before today and today
      return current && current < moment().subtract(1, 'days').endOf('day');
    },
    beforeUpload(file) {
      const isJpgOrPng =
        file.type === "image/jpeg" || file.type === "image/jpg" || file.type === "image/png" ;
      if (!isJpgOrPng) {
        this.$message.warning("请上传正确的文件格式");
        return false;
      }
      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!isLt2M) {
        this.$message.warning("请上传5M以内的大小图片");
        return false;
      }
      return isJpgOrPng && isLt2M;
    },

    handleChanger(info) {
      console.log(info);
      if (info.file.status === "uploading") {
        this.loading = true;
        return;
      }
      if (info.file.status === "done") {
        // Get this url from response in real world.

        let _files = {
          fileName: info.file.response.data.fileName,
          fileType: info.file.response.data.fileType,
          fileUrl: info.file.response.data.fileUrl,
          objectType: 1 //1:产品图片
        };
        this.formLine.productFile.push(_files);
      }
    },

    DelImag(id, index) {
      // console.log(id,index);
      this.formLine.productFile.splice(index, 1);
    },

    handleChanger1(info) {
      console.log(info);
      if (info.file.status === "uploading") {
        this.loading = true;
        return;
      }
      if (info.file.status === "done") {
        // Get this url from response in real world.

        let _files = {
          fileName: info.file.response.data.fileName,
          fileType: info.file.response.data.fileType,
          fileUrl: info.file.response.data.fileUrl,
          objectType: 2 //2:产品荣誉资质
        };
        this.formLine.honorFile.push(_files);
      }
    },

    DelImag1(id, index) {
      // console.log(id,index);
      this.formLine.honorFile.splice(index, 1);
    },
    checkChange(e) {
      this.checkNick = e.target.checked;
      if(this.checkNick){
        this.priceRules[0].required = false
      }else{
        this.priceRules[0].required = true
      }
      this.form.setFieldsValue({
        price:''
      })
    },
    inputChange(e){
      if(e!=''){
        this.checkNick = false
        this.priceRules[0].required = true
      }else{
        this.checkNick = true
        this.priceRules[0].required = false
      }
    },
    checkChange1(e) {
      this.checkNick1 = e.target.checked;
      if(this.checkNick1){
        this.productCeilingRules[0].required = false
      }else{
        this.productCeilingRules[0].required = true
      }
      this.form.setFieldsValue({
        productCeiling:''
      })
    },
    inputChange1(e){
      if(e!=''){
        this.checkNick1 = false
        this.productCeilingRules[0].required = true
      }else{
        this.checkNick1 = true
        this.productCeilingRules[0].required = false
      }
    },
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log("Received values of form: ", values);
          
          values.publishDate = moment(values.publishDate).format("YYYY-MM-DD");
          // this.formLine = values;
          let _newform = {}
          _newform = values
          this.$set(_newform,'productFile',this.formLine.productFile)
          this.$set(_newform,'honorFile',this.formLine.honorFile)
          this.formLine = _newform
          console.log(_newform)
          this.defultForm.productName =  _newform.productName;
          this.defultForm.productSynonymName =  _newform.productSynonymName;
          this.defultForm.productOneCategory =  _newform.productOneCategory;
          this.defultForm.productSecondCategory =  _newform.productSecondCategory;
          this.defultForm.productThirdCategory =  _newform.productThirdCategory;
          this.defultForm.productSpec =  _newform.productSpec;
          this.defultForm.productTag =  _newform.productTag;
          this.defultForm.productOem =  _newform.productOem;
          this.defultForm.publishDate =  _newform.publishDate;
          
          // this.defultForm.price =  _newform.price;
          if(this.checkNick==true){
            this.defultForm.isInterview = 1
            this.defultForm.price = 0
          }else{
            this.defultForm.isInterview = 0
            this.defultForm.price =  _newform.price
          }
          // this.defultForm.productCeiling =  _newform.productCeiling;
          if(this.checkNick1==true){
            this.defultForm.productIslimited = 1
            this.defultForm.productCeiling = ''
          }else{
            this.defultForm.productIslimited = 0
            this.defultForm.productCeiling =  _newform.productCeiling
          }
          // this.defultForm.productIslimited =  _newform.productIslimited;
          this.defultForm.productFile =  _newform.productFile;
          this.defultForm.honorFile =  _newform.honorFile;
          this.defultForm.productParam =  _newform.productParam;
          this.defultForm.productDetails =  _newform.productDetails;
          this.defultForm.contacts =  _newform.contacts;
          this.defultForm.phone =  _newform.phone;
          this.defultForm.email =  _newform.email;
          console.log('----------------')
          console.log(this.defultForm)
          this.Updateproduct();
          // 清空表单
          this.form.resetFields();
        }
      });
    },
    clear() {
      //跳回需求页
      this.$router.push("/usercenter/MyProduct");
    },
    // 修改
    Updateproduct() {
      Updateproduct(this.defultForm).then(res => {
        console.log(res);
        if(res.code==200){
          this.$message.success("修改成功");
          setTimeout(() => {         
            //跳回需求页
            this.$router.push("/usercenter/MyProduct");
          }, 1000);
        }else{
          this.$message.warning('修改失败');
        }
      });
    },
    //获取详情
    GetproductDetail(){
      GetproductDetail({id:this.productId}).then((res)=>{
        console.log('获取详情')
        console.log(res)
        if(res.code == 200){
          this.defultForm = res.data
          this.$refs.editor.editor.txt.html(this.defultForm.productDetails)
          if(this.defultForm.productIslimited==1){
            this.checkNick1 = true

          }else{
            this.checkNick1 = false
          }
          if(this.defultForm.isInterview==1){
            this.checkNick = true
            if(this.checkNick){
              this.priceRules[0].required = false
            }else{
              this.priceRules[0].required = true
            }
            this.form.setFieldsValue({
              price:''
            })
          }else{
            this.checkNick = false
          }
          this.formLine.productFile=res.data.productFile
          this.formLine.honorFile=res.data.honorFile
          // console.log(this.defultForm)
          // console.log(this.formLine)
          let id = '';
          this.selectType.map((item, index) => {
            if (item.categoryNo == this.defultForm.productOneCategory) {
              id = item.id;
            }
          });
          let params = { pid:id };
          // console.log(params)
          GetByParent(params).then(res => {
            console.log(res);
            if (res.code == 200) {
              this.selectType1 = res.data;
            }
          });
        }
      })
    },
    // 产品分类下拉列表
    GetByParentList() {
      GetByParent().then(res => {
        // console.log(res)
        if (res.code == 200) {
          this.selectType = res.data;
        }
      });
    },
    handleChange(value) {
      console.log(value);
      let id = "";
      this.selectType.map((item, index) => {
        if (item.categoryNo == value) {
          id = item.id;
        }
      });
      let params = { pid: id };
      GetByParent(params).then(res => {
        console.log(res);
        if (res.code == 200) {
          this.selectType1 = res.data;
        }
      });
    },
    handleChange1(value) {
      console.log(value);
    }
  }
};
</script>

<style lang="less" scoped>
.ant-form-item {
  margin-bottom: 8px;
}
.ProductsRelease {
  padding: 17px 24px;
  background: #fff;
  h2 {
    font-size: 22px;
    line-height: 17px;
    color: #303133;
    padding-bottom: 14px;
    border-bottom: solid 1px #e9e9e9;
  }

  .main {
    pointer-events: none;
    h3 {
      margin: 16px 0;
      padding-left: 16px;
      height: 48px;
      line-height: 48px;
      font-weight: 700;
      font-size: 16px;
      color: #303133;
      background-color: #f5f7fa;
      border-radius: 4px;
    }
  }
}
em {
  font-size: 14px;
  color: #909399;
}

/deep/.w-e-text {
  min-height: 500px;

  max-height: 500px;
}
.img-box {
  position: relative;
  border: 1px solid #e8e8e8;
  margin-bottom: 10px;
  width: 104px;
  height: 104px;
  img {
    width: 100%;
    height: 100%;
    // object-fit: cover;
  }
  &:hover {
    .close {
      display: block;
    }
  }
  .close {
    position: absolute;
    top: -10px;
    right: -10px;
    color: #fff;
    width: 20px;
    height: 20px;
    font-size: 20px;
    z-index: 99;
    background-color: red;
    border-radius: 100%;
    cursor: pointer;
    display: none;
  }
}
</style>